/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
/**
 * Created by ued on 2017/3/6.
 */

import Vue from 'vue';
import co from 'src/util/co_not_reject';
import IntervalTask from 'src/util/interval_task';

const INTERVAL = 60000;
let vm = new Vue();

class Branch {

    constructor (options) {
        this.task = new IntervalTask(Object.assign({
            interval: INTERVAL,
            fn: this.getBranchInfo.bind(this),
            autoStart: false,
            skipFirst: true
        }, options));
    }

    getBranchInfo () {
        let me = this;

        return co(function * () {
            let { jsonData } = yield vm.$http.get('branch/get_branch_info');

            me.task.next();

            if (!jsonData.success) {
                return;
            }

            window.SHARED.$root.$store.dispatch('setBranchInfoList', jsonData);
        });
    }

    run () {
        this.task.start();
    }

    stop () {
        this.task.stop();
    }

}

let branchTask = new Branch();
let hasInitBranch = false; // 记录是否已经加载过分支数据了

function start () {
    if (!hasInitBranch) {
        hasInitBranch = true;
        branchTask.getBranchInfo().then(() => {
            branchTask.run();
        });
    } else {
        branchTask.run();
    }

}

function stop () {
    branchTask.stop();
}

export default {
    start,
    stop
};
